﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml.Linq;

namespace Tiger.Common
{
    public class XmlUtil
    {
        /// <summary>
        /// 解析XML格式
        /// <root><item><key></key><value></value></item></root>
        /// </summary>
        /// <param name="xmlString"></param>
        /// <returns></returns>
        public static Dictionary<string, string> ParseXml(string xmlString)
        {
            Dictionary<string, string> dict = new Dictionary<string, string>();
            System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
            xmlDoc.LoadXml(xmlString);
            System.Xml.XmlNodeList nodeList = xmlDoc.GetElementsByTagName("item");
            foreach(System.Xml.XmlNode node in nodeList)
            {
                dict.Add(node["key"].InnerText, node["value"].InnerText);
            }

            return dict;
        }

        /// <summary>
        /// 解析XML格式:可能有重复值
        /// <root><key1></key1><key2></key2></root>
        /// </summary>
        /// <param name="xmlString"></param>
        /// <returns></returns>
        public static List<KeyValuePair<string, string>> ParseXml2(string xmlString)
        {
            List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>();
            System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
            xmlDoc.LoadXml(xmlString);
            foreach (System.Xml.XmlNode node in xmlDoc.DocumentElement.ChildNodes)
            {
                list.Add(new KeyValuePair<string, string>(node.Name, node.InnerText));
            }

            return list;
        }

        /// <summary>
        /// 构造提交表单
        /// </summary>
        /// <param name="originXML"></param>
        /// <param name="paramList">
        /// 参数格式：{"Col":"2","Row":"3","Value":"梁威","InternalValue":"100001"}
        /// </param>
        public static string ConstructXML(string originXML, List<Dictionary<string, string>> paramList)
        {
            try
            {
                var doc = XDocument.Parse(originXML);

                foreach (Dictionary<string, string> dict in paramList)
                {
                    XElement element = doc.Descendants("Cell")
                    .Where(arg => arg.Attribute("Col").Value == dict["Col"] && arg.Attribute("Row").Value == dict["Row"]).FirstOrDefault();
                    if (dict["Value"] != null)
                    {
                        element.Add(new XAttribute("Value", dict["Value"]));
                    }
                    if (dict["InternalValue"] != null)
                    {
                        element.Add(new XAttribute("InternalValue", dict["InternalValue"]));
                    }
                }
                return doc.ToString();
            }
            catch (Exception e)
            {
                throw e;
            }
        }
    }
}